package com.donfelix.looknews.view.implpresenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.donfelix.looknews.api.ApiManager;
import com.donfelix.looknews.bean.image.ImageResponse;
import com.donfelix.looknews.view.implview.IMain;
import com.donfelix.looknews.view.presenter.IMainPresenter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Don on 2017/3/27.
 * Desc
 */

public class MainPresenterImpl extends BasePresenterImpl implements IMainPresenter {
    private IMain main;
    private Context context;

    public MainPresenterImpl(IMain main, Context context) {
        if (main == null) {
            throw new IllegalArgumentException("main can't be null");
        }
        this.main = main;
        this.context = context;
    }

    @Override
    public void getBackground() {
        ApiManager.getInstance().getZhihuApiService().getImage()
                .subscribeOn(Schedulers.io())
                .map(new Function<ImageResponse, String>() {
                    @Override
                    public String apply(@NonNull ImageResponse imageResponse) throws Exception {
                        String description = null;
                        if (imageResponse.getData() != null && imageResponse.getData().getImages() != null) {
                            try {
                                String base_url = imageResponse.getData().getBase_url();
                                String image_url = imageResponse.getData().getImages().get(0).getImage_url();
                                description = imageResponse.getData().getImages().get(0).getDescription();
                                Bitmap bitmap = BitmapFactory.decodeStream(
                                        new URL(base_url + image_url + "?imageMogr/v2/auto-orient/thumbnail/480x320/quality/100").openConnection().getInputStream());
                                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File(context.getFilesDir().getPath() + "/bg.jpg")));

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        return description;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(@NonNull String s) throws Exception {
                        main.getPic(s);
                    }
                });
    }
}
